package com.dyl.sms.controller;


import com.dyl.common.core.RR;
import com.dyl.sms.service.SmsService;
import com.dyl.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description="阿里云短信服务")
@RestController
@RequestMapping("/dylSms")
@CrossOrigin
public class SmsApiController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "短信发送")
    @GetMapping("sendSmsPhone/{phone}")
    public RR sendSmsPhone(@PathVariable String phone){
        //1 拿手机号到redis查询验证码
        String rPhone = redisTemplate.opsForValue().get(phone);
        //2验证验证码是否存在，直接返回ok
        if(rPhone!=null){
            return RR.ok();
        }
        //3验证码不存在，生成验证码
        String code = RandomUtil.getFourBitRandom();
        //4调用接口服务发送短信
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        boolean isSend = smsService.sendSmsPhone(phone,map);
        //5发送成功验证码存入redis，时效1分钟
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return RR.ok();
        }else{
            return RR.error();
        }

    }

    @ApiOperation(value = "验证码判断")
    @GetMapping("querySmsPhone/{phone}/{codes}")
    public RR querySmsPhone(@PathVariable String phone,@PathVariable String codes){
        String redisCode = redisTemplate.opsForValue().get(phone);
        if(!codes.equals(redisCode)){
            return RR.error().message("验证码错误").code(500);
        }
        return RR.ok().code(200);
    }

}
